package com.cudex.mb;

import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cudex.negocio.beans.Empleado;
import com.cudex.negocio.factory.IBarracaManager;
import com.cudex.negocio.utils.FacesUtils;

@ManagedBean
@SessionScoped
public class LoginBean {

	private static final Logger log = Logger.getLogger(LoginBean.class
			.getName());

	@EJB
	IBarracaManager manager;

	private Empleado logedUser;
	private String user;
	private String pass;
	private String logueado;

	public LoginBean() {
		// TODO Auto-generated constructor stub
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getLogueado() {
		return logueado;
	}

	public void setLogueado(String logueado) {
		this.logueado = logueado;
	}

	/**
	 * @return the logedUser
	 */
	public Empleado getLogedUser() {
		return logedUser;
	}

	/**
	 * @param logedUser
	 *            the logedUser to set
	 */
	public void setLogedUser(Empleado logedUser) {
		this.logedUser = logedUser;
	}

	public String ingreso() {
		log.info("ingreso()");
		String res = null;

		logedUser = manager.loginUsuario(getUser(), getPass());
		if (logedUser != null) {
			setSession(logedUser);
			//res = "ingreso.xhtml";
			res = "dashboard.xhtml";
		} else {
			res = "login.xhtml";
			FacesUtils.setMessage("Error al intentar loguearse");
		}
		return res;
	}

	public String salir() {
		log.info("Salir invocado.");
		userLogout();
		String res = "login.xhtml?faces-redirect=true";
		return res;
	}

	private void setSession(Empleado e) {
		HttpServletRequest request = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		HttpSession session = request.getSession();
		session.setAttribute("user", e);

	}

	private void userLogout() {
		// HttpServletRequest request = (HttpServletRequest) FacesContext
		// .getCurrentInstance().getExternalContext().getRequest();
		// request.getSession().invalidate();

		FacesContext fc = FacesContext.getCurrentInstance();

		// invalidate session
		ExternalContext ec = fc.getExternalContext();
		HttpSession session = (HttpSession) ec.getSession(false);
		session.invalidate();
//
//		// redirect to the login / home page
//		try {
//			ec.redirect(ec.getRequestContextPath()+"?faces-redirect=true");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
}
